package com.app.bimo.module_accounts.service;

import android.content.Context;
import android.util.Log;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.app.bimo.commonbusiness.bean.BaseResult;
import com.app.bimo.commonbusiness.eventdata.ErrorGetUserInfo;
import com.app.bimo.commonbusiness.eventdata.FinishGetUserInfo;
import com.app.bimo.commonbusiness.network.RetrofitServiceManager;
import com.app.bimo.commonbusiness.network.RxObservableUtil;
import com.app.bimo.commonbusiness.util.Constant;
import com.app.bimo.commonbusiness.util.DataUtil;
import com.app.bimo.commonbusiness.util.LoginService;
import com.app.bimo.commonbusiness.util.RouterHub;
import com.app.bimo.commonbusiness.util.RxBus;
import com.app.bimo.commonbusiness.util.SharedPreUtils;
import com.app.bimo.commonbusiness.util.SystemUtil;
import com.app.bimo.library_db.ADConfigResultData;
import com.app.bimo.library_db.UserData;
import com.app.bimo.library_db.helper.AdHelper;
import com.app.bimo.library_db.helper.UserHelper;
import com.app.bimo.module_accounts.BuildConfig;
import com.app.bimo.module_accounts.mvp.model.entiy.OtherResult;

import java.util.concurrent.TimeUnit;

import androidx.collection.ArrayMap;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DefaultObserver;
import io.reactivex.schedulers.Schedulers;

@Route(path = RouterHub.ACCOUNT_SERVICE)
public class AccountService implements LoginService {
    private Context context;
    private boolean isNoInit = true;

    @Override
    public void init(Context context) {
        this.context = context;
    }

    public boolean isLogin() {
        UserData data = UserHelper.getsInstance().findUser();
        if (data != null) {
            return true;
        }
        return false;
    }


    @Override
    public boolean isRealLogin() {
        return SharedPreUtils.getInstance(context).getBoolean(Constant.isRealLogin, false);
    }

    @Override
    public String getToaken() {
        return SharedPreUtils.getInstance(context).getString(Constant.HttpToken);
    }

    @Override
    public void removeToaken() {
        RetrofitServiceManager.getInstance().removeAllHead(Constant.HttpToken);
        SharedPreUtils.getInstance(context).putString(Constant.HttpToken, "");
        UserHelper.getsInstance().removeUser();
    }


    /**
     * 幽灵账号登录
     */
    public void devicesLogin(boolean isHome) {
        ArrayMap map = new ArrayMap();
        map.put("type", "5");
        map.put("openid", SystemUtil.getIMEI(context));
        String fromChannel = SharedPreUtils.getInstance(context).getString(Constant.fromChannel);
        String fromChannelUsed = SharedPreUtils.getInstance(context).getString(Constant.fromChannelUsed);
        if (DataUtil.isEmpty(fromChannelUsed) && !DataUtil.isEmpty(fromChannel)) {
            map.put("fromChannel", fromChannel);
        }
        Observable<BaseResult<OtherResult>> observable;
        if (isHome) {
            observable = RetrofitServiceManager.getInstance().createRetrofit(BuildConfig.APPLICATION_ID,
                    com.app.bimo.module_accounts.mvp.model.api.service.AccountService.class)
                    .login(map)
                    .timeout(2500, TimeUnit.MILLISECONDS)
            ;
        } else {
            observable = RetrofitServiceManager.getInstance().createRetrofit(BuildConfig.APPLICATION_ID,
                    com.app.bimo.module_accounts.mvp.model.api.service.AccountService.class)
                    .login(map)
                    .timeout(2, TimeUnit.MINUTES)
            ;
        }

        if (isNoInit) {
            isNoInit = false;
            RetrofitServiceManager.getInstance().removeAllHead(Constant.HttpToken);
            observable.subscribeOn(Schedulers.io()) //指定耗时进程
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new DefaultObserver<BaseResult<OtherResult>>() {
                        @Override
                        public void onNext(BaseResult<OtherResult> otherResultBaseResult) {
                            if (otherResultBaseResult.getCode() == 200) {
                                SharedPreUtils.getInstance(context).putString(Constant.fromChannelUsed, Constant.fromChannelUsed);
                                SharedPreUtils.getInstance(context).putString(Constant.HttpToken, otherResultBaseResult.getResult().getToken());
                                RetrofitServiceManager.getInstance().addAllHead(Constant.HttpToken, otherResultBaseResult.getResult().getToken());
                                if (UserHelper.getsInstance().findUser() != null) {
                                    UserHelper.getsInstance().removeUser();
                                }
                                UserHelper.getsInstance().saveUser(otherResultBaseResult.getResult().getUserInfo());
                                RxBus.getInstance().post(new FinishGetUserInfo());
                                if (otherResultBaseResult.getResult().getUserInfo().getChannel() == 1 || otherResultBaseResult.getResult().getUserInfo().getChannel() == 2) {
                                    SharedPreUtils.getInstance(context).putBoolean(Constant.settingPreSucess, true);
                                }
                                SharedPreUtils.getInstance(context).putBoolean(Constant.isRegister, otherResultBaseResult.getResult().getIsRegister() == 1);
                                isNoInit = true;
                            } else {
                                RxBus.getInstance().post(new ErrorGetUserInfo());
                                isNoInit = true;
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                            Log.i("response",e.getMessage()+ e.getLocalizedMessage() + e.toString());
                            isNoInit = true;
                            RxBus.getInstance().post(new ErrorGetUserInfo());
                        }

                        @Override
                        public void onComplete() {

                        }
                    });

        }
    }


    @Override
    public boolean isVip() {
        UserData userData = UserHelper.getsInstance().findUser();
        if (userData == null) {
            return false;
        } else {
            return userData.getIsVip() == 1;
        }
    }

    /**
     * channel 1 男  2 女
     *
     * @return
     */
    public int getChannel() {
        UserData userData = UserHelper.getsInstance().findUser();
        if (userData == null) {
            return 1;
        } else {
            return userData.getChannel();
        }
    }

    @Override
    public boolean isRealUser() {
        UserData data = UserHelper.getsInstance().findUser();
        if (data != null) {
            return data.getType() == 2;
        }
        return false;
    }

    /**
     * channel 手机号
     *
     * @return
     */
    public String getMobile() {
        UserData userData = UserHelper.getsInstance().findUser();
        if (userData == null) {
            return "";
        } else {
            return userData.getMobile();
        }
    }

    @Override
    public String getUserBookcoin() {
        UserData userData = UserHelper.getsInstance().findUser();
        if (userData == null) {
            return "0";
        } else {
            return userData.getBookCoinInt() + "";
        }
    }

    public void getUserInfo() {
        Observable<UserData> userDataObservable = RxObservableUtil.compose(RetrofitServiceManager.getInstance().createRetrofit(BuildConfig.APPLICATION_ID, com.app.bimo.module_accounts.mvp.model.api.service.AccountService.class).getUserInfo());
        userDataObservable.subscribe(new DefaultObserver<UserData>() {
            @Override
            public void onNext(UserData userData) {
                UserHelper.getsInstance().saveUser(userData);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    @Override
    public void getADConfig() {
        Observable<ADConfigResultData> userDataObservable = RxObservableUtil.compose(RetrofitServiceManager.getInstance().createRetrofit(BuildConfig.APPLICATION_ID, com.app.bimo.module_accounts.mvp.model.api.service.AccountService.class).getConfig());
        userDataObservable.subscribe(new DefaultObserver<ADConfigResultData>() {
            @Override
            public void onNext(ADConfigResultData userData) {
                AdHelper.getsInstance().save(userData);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }


    @Override
    public void getBaseUrl() {
//        String url = "https://bimo-novel-image.oss-cn-shenzhen.aliyuncs.com/env_dev/passport/list.txt";

    }

    @Override
    public void putCid(String cid) {
        Observable<String> userDataObservable = RxObservableUtil.compose(RetrofitServiceManager.getInstance().createRetrofit(BuildConfig.APPLICATION_ID, com.app.bimo.module_accounts.mvp.model.api.service.AccountService.class).putCid(cid));
        userDataObservable.subscribe(new DefaultObserver<String>() {
            @Override
            public void onNext(String userData) {
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    @Override
    public void setAccountLike(int isRegiest) {
        Observable<Object> userDataObservable = RxObservableUtil.compose(RetrofitServiceManager.getInstance().
                createRetrofit(BuildConfig.APPLICATION_ID, com.app.bimo.module_accounts.mvp.model.api.service.AccountService.class).
                setPre(3, "", isRegiest));
        userDataObservable.subscribe(new DefaultObserver<Object>() {
            @Override
            public void onNext(Object userData) {
                SharedPreUtils.getInstance(context).putBoolean(Constant.settingPreSucess, true);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }


    public void changeUserBookcoin(int coin) {
        UserData userData = UserHelper.getsInstance().findUser();
        if (userData != null) {
            userData.setBookCoin(userData.getBookCoin() - coin);
        }
    }

    @Override
    public String getUserId() {
        UserData userData = UserHelper.getsInstance().findUser();
        if (userData != null) {
            return userData.getUuid();
        }
        return null;
    }
}
